package gameframework;



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;







public class Game {
	//mang object ngan
	public ArrayList<ngan> nganlist=new ArrayList<ngan>();
	//thay doi hinh game
	  private String hinhnen="hinhnen";
	//mang nhung trung ga
private ArrayList<TrungGa> trungalist= new ArrayList<TrungGa>();

//hinh nen
	  private BufferedImage hinhnengame;
	  //hinh shit
	 // private BufferedImage hinh_shit;
	    //ngau nhien tao trung
	  Random ran=new Random();
	//khung vien khi thua
	    private BufferedImage khungvien;
	    //them ga
	    private BufferedImage con_ga;
	    private RoTrung rotrung;
	    // hinh trung be   
	    private BufferedImage hinh_trung_ga_be;
	    //anim be trung
	    private ArrayList<Animation> betrungga;
	    //khoi tao ga
	    private ConGa conga;
	    
	    private ngan Ngan;
	    //
	    private BufferedImage hinh_chathay;
	    private int trungroingoairo;
	    private int trungbatduoc;    
	    private int shit;
	    
	    //bien de chay trung hoac shit
	    private String ngaunhien;
	    String tamngaunhien;
	    //font
	   
	    private Font font;
	    
	  //xet va cham voi shit,xem la shit hay la trung
	    boolean la_shit;
	    //level
	    int level;
	    // code framework
    public Game()
    {
    	
    	
        Framework.gameState = Framework.GameState.GAME_CONTENT_LOADING;
        
        Thread threadForInitGame = new Thread() {
            @Override
            public void run(){
                // Sets variables and objects for the game.
                Initialize();
                // Load game files (images, sounds, ...)
                LoadContent();
                
                Framework.gameState = Framework.GameState.PLAYING;
            }
        };
        threadForInitGame.start();
    }
    
    
   /**
     * Set variables and objects for the game.
     */
    // Given time in seconds.
    private void Initialize()
    {
    		shitoregg();
    		rotrung =new RoTrung((int)(Framework.frameWidth * 0.46),(int)(Framework.frameHeight * 0.88));
    		conga =new ConGa();
    		
    		trungalist =new ArrayList<TrungGa>();
    		nganlist =new ArrayList<ngan>();
    		Ngan =new ngan();
    		   betrungga = new ArrayList<Animation>();
    		   level=1;
    		 //  tao_ngan();
    		
    }
    
    /**
     * Load game files - images, sounds, ...
     */
    // Given time in seconds.
    private void LoadContent()
    {
    	
    	try {
    		URL backgroundImgUrl = this.getClass().getResource("/gameframework/resources/images/"+hinhnen+".jpg");
            hinhnengame = ImageIO.read(backgroundImgUrl);
            
            URL redBorderImgUrl = this.getClass().getResource("/gameframework/resources/images/red_border.png");
           khungvien = ImageIO.read(redBorderImgUrl);
           
           //ga them
         ran.equals(hinh_trung_ga_be);
          // URL them_ga = this.getClass().getResource("/gameframework/resources/images/ga.png");
        //  con_ga = ImageIO.read(them_ga);
         
         //bi bien 
           //URL trung_ga = this.getClass().getResource("/gameframework/resources/images/egg.png");
             //TrungGa.hinh_trung_ga = ImageIO.read(trung_ga);
             //trung be
             URL trung_be_anim = this.getClass().getResource("/gameframework/resources/images/trungbe.jpg");
             hinh_trung_ga_be = ImageIO.read(trung_be_anim);
             //chat thai
             URL chatthay = this.getClass().getResource("/gameframework/resources/images/trungno.png");
             hinh_chathay = ImageIO.read(chatthay);
             //
             URL shit = this.getClass().getResource("/gameframework/resources/images/"+ngaunhien+".png");
             TrungGa.hinh_shit_or_egg = ImageIO.read(shit);
        
		} catch (Exception ex) {
			Logger.getLogger(Game.class.getName()).log(Level.SEVERE, null, ex);
        
		}
    }    
    
    
    /**
     * Restart game - reset some variables.
     */
    // khoi tao lai ban dau
    public void RestartGame()
    {
        TrungGa.khoitaolaibandau();
        Ngan.khoitaolai(0,0);
     //   rotrung.khoitao_lai(x_re, y_re)
        //int xmoi=(int)(Framework.frameWidth * 0.46);
       // int ymoi=(int)(Framework.frameHeight * 0.88);
        rotrung.khoitao_lai((int)(Framework.frameWidth * 0.46),(int)(Framework.frameHeight * 0.88));
        conga.khoitaolai(0);
        //lam moi list
        trungalist.clear();
        betrungga.clear();
       nganlist.clear();
        //ve ban dau
        trungroingoairo=0;
        trungbatduoc=0;
        shit=0;
        level=1;
        hinhnen="hinhnen";    
        LoadContent();
        }
    
    
    /**
     * Update game logic.
     * 
     * @param gameTime gameTime of the game.
     * @param mousePosition current mouse position.
     */
    // ham nay se chay lien tuc vi duoc goi ben framework.gameloop
    public void UpdateGame(long gameTime, Point mousePosition)
    {
    	if(!kiemtragame())//&& betrungga.isEmpty() )
    	{
    		Framework.gameState=Framework.GameState.GAMEOVER;
    		return;
    		
    	}
        rotrung.update();
       // 
        
		
			
        conga.update();
        Ngan.Update();
      
       
		
		
        //trung ga	
        taotrungga(gameTime);
        capnhat_trungga();
        //cap nhat vu no
        capnhatvuno();
        //cap nhat vi tri moi cua chuot
        if(Canvas.mouseButtonState(1)){
        	rotrung.x=mousePosition.x;
        	
        	
        }
   
   
        
    }
  
    
     
    
    // code tu viet
    //hien thi thoii gian,doi ra giay ve  
    private static String formatTime(long time){
 
        int sec = (int)(time / Framework.milisecInNanosec / 1000);

        // Given time in minutes and seconds.
        int min = sec / 60;
        sec = sec - (min * 60);

        String minString, secString;

        if(min <= 9)
            minString = "0" + Integer.toString(min);
        else
            minString = "" + Integer.toString(min);

        if(sec <= 9)
            secString = "0" + Integer.toString(sec);
        else
            secString = "" + Integer.toString(sec);

        return minString + ":" + secString;
}
    // code tu viet
    //ve hinh trung ga,con ga, animation
    public void Draw(Graphics2D g2d, Point mousePosition,long gameTime)
    {
    	
    	g2d.drawImage(hinhnengame, 0, 0, Framework.frameWidth, Framework.frameHeight, null);
    	conga.Draw(g2d);
    	
    	//
    	if(Canvas.mouseButtonState(1)){
    	rotrung.Draw(g2d,mousePosition);
    	}
    	else {
    	rotrung.Draw2(g2d);
    	}
    	//
    	  for(int i = 0; i < trungalist.size(); i++)
          {
              trungalist.get(i).Drawn(g2d);
          }
    	  for(int i = 0; i < betrungga.size(); i++)
          {
              betrungga.get(i).Draw(g2d);
          }
    	  for(int i = 0; i < nganlist.size(); i++)
          {
              nganlist.get(i).Drawn(g2d);
          }
    	  //
          
    	  //statictis
    	  g2d.setFont(font);
          g2d.setColor(Color.red);
          
    	 g2d.drawString(formatTime(gameTime), Framework.frameWidth/2 - 45, 21);
         g2d.drawString("Trứng trong rổ: " + trungbatduoc, 10, 21);
         g2d.drawString("Trứng rơi ngoài rổ:  "    + trungroingoairo,   10, 41);
         g2d.drawString("shit hứng được: "   + shit,   10, 60);
         g2d.drawString("có "+level+"0 con gà",555,21);
    }
    // code tu viet
    private void tao_ngan()
    {
    	
    		ngan n=new ngan();
    		int xngan_khoitao=ran.nextInt(Framework.frameWidth-ngan.hinh_ngan.getWidth());
    		int yngna_khoitao=ngan.hinh_ngan.getHeight();
    		//n.khoitaolai(xngantaolai, yngantaolai);
    		//n.x_ngan=xx;
    		//n.y_ngan=yy;
    		n.them(xngan_khoitao, 0);
    		nganlist.add(n);
    		
   
    	
    }
    //man hinh ket thuc game
    // code tu viet
   // goi khi ket thuc game
    public void ketthucgame(Graphics2D g2d,Point mousePosition,long thoigian)
    {
    	
    	g2d.drawString("Press space or enter to restart.", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3 +100);
    	
    	
    	
    	
    		g2d.drawString("Thua rùi!", Framework.frameWidth / 2 - 100, Framework.frameHeight/3 - 10);
    		g2d.drawString("Thời gian thu hoạch!"+ thoigian / Framework.secInNanosec + " seconds.", Framework.frameWidth / 2 - 100, Framework.frameHeight / 3 + 20);
    		g2d.drawString("Số lượng trứng trong rổ"+ trungbatduoc , Framework.frameWidth / 2 - 95, Framework.frameHeight / 3+50);
    		
   
    	
    }
    //tao ra trung ga
   
	//System.out.print(mot_hay_2);
    // code tu viet
    //tao trung ga va bo vao mag khoang 5s
    private void taotrungga(long gameTime)
    {
    	
 
		
    	if(gameTime-TrungGa.thoigiantangcuatrungcuoicung>=TrungGa.thoigiangiua2_trung_duoctao)
    	{
    		
    		TrungGa tg=new TrungGa();
    		int x_khoitao=ran.nextInt(Framework.frameWidth-TrungGa.hinh_shit_or_egg.getWidth());
    		int x_khoitao2=ran.nextInt(ConGa.x+ConGa.tocdo_x);
    		int y_khoitao=Framework.frameHeight;
    		tg.Initialize(x_khoitao, conga.chieu_cao_ga);
    		
    		trungalist.add(tg);
    		//tang toc do
    		//khi dat duoc 20 trung
    		if(trungbatduoc>=2*level)
    		{
    			level++;
    			TrungGa.tangtaodo();
    			
    			// xay them khi tang cap
    			switch (level) {
				case 2:
					hinhnen="hinhnen1";
					LoadContent();
					break;
					
				default:
					break;
				}
    		}
    		//dat  thoi gian khaong cach trug duoc tao ra.
    		TrungGa.thoigiantangcuatrungcuoicung = gameTime;
    	
    	}
   	 }
    // code tu viet
 //   cap nhat trung bat cac su kien cua trứng và shit
   public void capnhat_trungga()
   {
	   for(int i=0;i<trungalist.size();i++)
	   {
		  TrungGa tg= trungalist.get(i);
		   tg.Update();
		   
		   //dua vao hinh de xac dinh va cham
		   Rectangle ro =new Rectangle(rotrung.x,rotrung.y,rotrung.Ro_Trung.getWidth()/2,rotrung.Ro_Trung.getHeight()/2);
		   Rectangle trung=new Rectangle(ConGa.x,tg.y_trung,TrungGa.hinh_shit_or_egg.getWidth()/2,TrungGa.hinh_shit_or_egg.getHeight()/2);
		   if( tg.kiemtra_trung() && la_shit==false){
			   trungroingoairo++;
			   trungalist.remove(i);
			   shitoregg();
			   
			   //anim
			   for(int solan=0;solan<1;solan++)
			   {
				   
				  Animation an=new Animation(hinh_trung_ga_be,  134, 89, 122, 245,false,ConGa.x,trung.y,1);// solan * 200 +ran.nextInt(100)) ;
				   betrungga.add(an);
			   }
			   	break;
		   }
		   else if(ro.intersects(trung) && la_shit==true){
		    	
		    	shit++;
		    	
		    	shitoregg();
		    	trungalist.remove(i);
		    	
		   }
		   
		   
		   else  if(ro.intersects(trung) && la_shit==false)
	            {
	               
	                trungbatduoc++;
	                trungalist.remove(i);
	                shitoregg();
	            }
		   else if(tg.kiemtra_trung() && la_shit==true)
		   {
			   
			   for(int solan=0;solan<3;solan++)
			   {
				   
				  Animation an=new Animation(hinh_chathay,  134, 134, 12, 45,false,ConGa.x-ran.nextInt(100),trung.y - solan*60, solan * 200 +ran.nextInt(100)) ;
				  betrungga.add(an);
			   }
			   trungalist.remove(i);
			   shitoregg();
		   }
	  }
 }
	   
   
   // code tu viet
   //kiem tra animation da active chua va huy
   private void capnhatvuno()
   {
       for(int i = 0; i < betrungga.size(); i++)
       {
           if(!betrungga.get(i).active)
               betrungga.remove(i);
       }
   }
   // code tu viet
   //kiểm tra dừng game
   public boolean kiemtragame()
   {
	   if(trungroingoairo>=3||shit>=3)
		   return false;
	   return true;
   }
   //thống kê khi kết thức game
   public void Drawthongke(Graphics2D g2d, long gameTime){
       g2d.drawString("thoi gian: " + formatTime(gameTime),                Framework.frameWidth/2 - 50, Framework.frameHeight/3 + 80);
      
       g2d.drawString("trung thu hoach duoc: " + trungbatduoc,       Framework.frameWidth/2 - 65, Framework.frameHeight/3 + 150);
       g2d.drawString("roi ra ngoai: "   + trungroingoairo,         Framework.frameWidth/2 - 65, Framework.frameHeight/3 + 170);
     
       g2d.drawString("thong ke: ",                                 Framework.frameWidth/2 - 75, Framework.frameHeight/3 + 60);
   }
   //random hinh
   // code tu viet
   //phat sinh ngau nhien va kiem tra bien ngau nhien la shit hay la trứng
   public String shitoregg()
	{
		
		int mot_hay_2=ran.nextInt(2);
		//System.out.print(mot_hay_2);
		la_shit=false;
		if(mot_hay_2==1)
		{
			ngaunhien="egg";
			//return ngaunhien;
			
		}
		else if(mot_hay_2==0)
		{
			ngaunhien="shit";
			la_shit=true;
		}
		//System.out.print(ngaunhien);
		LoadContent();
		return ngaunhien;
	
	}
}
